package ia.programas.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;



/**
 * Clase principal del servidor de aplicaciones.
 * @author Armando Andini
 *
 */
public class AppServer extends Thread{
	protected static int PUERTO = 1440;
	
	protected ServerSocket serverSocket;
	protected int puerto;
	protected static Logger logger = Logger.getLogger("AppServer");
	protected static boolean modoDebug = true;
	
	static public void log(String msg){
		System.out.println(msg);
	}
	static public void logd(String msg){
		if(modoDebug)
			log("[debug] "+ msg);
	}
	static public void loge(String msg){
		log("[error]"+msg);
	}
	
	public static void main(String[] args) {
		try {
			new AppServer(PUERTO);
		} catch (IOException e) {
			log("No se puede bindear al puerto "+PUERTO);
		}
	}
	
	public AppServer(int port) throws IOException{
		this.puerto = port;
		
		log("Intentando iniciar AppServer en puerto "+port);
		serverSocket=new ServerSocket(port);
		log("Escuchando en el puerto "+port+"...");
		this.start();
	}
	
	/**
	 * aceptar conexiones y crear hilos para administrar cada cliente
	 */
	public void run(){
		while(true){
			Socket clientSocket = null;
			try{
				clientSocket = serverSocket.accept();
				
			}
			catch(Exception e){
				continue;
			}
			try{
				logd("Nuevo cliente: "+clientSocket.getInetAddress().getHostAddress());
				InstanciaCliente cliente = new InstanciaCliente(clientSocket);
				cliente.start();
			}
			catch(Exception e){
				logd("No se pudo establecer conexion con "+clientSocket.getInetAddress().getHostAddress());
			}
			
			
		}
	
	}
	
}
